﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class WorkOrderControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!Page.IsPostBack)
            {
                SetDefaultState();
            }
        }
        private void SetDefaultState()
        {
            if (Request.QueryString["action"] == "add")
            {
                btnEditWorkOrder.Visible = false;
                btnSaveWorkOrder.Visible = true;
                btnRemoveWorkOrder.Visible = false;
                //btnCancel.Visible = true;
                DateTime startdt = DateTime.Now;
                txtStartTime.Text = startdt.ToShortTimeString();
                txtStartDate.Text = startdt.ToShortDateString();
                btnRollbackWorkOrderIntoEstimate.Visible = false;
            }
        }

        //protected void btnCancel_Click(object sender, EventArgs e)
        //{
        //    Response.Redirect(Request.RawUrl);
        //}
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string prevurl = string.Empty;
            int locationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();
            if (prevurl.Contains("RSLocationHistory") || prevurl.Contains("RSWorkOrderDetail"))
                Response.Redirect("~/RS/SBM/RSLocationHistoryWorkOrders.aspx?locationid=" + locationId);
            else
                Response.Redirect(prevurl);
        }
        public void SetControlEnabledState(bool bstate = false)
        {

            RSSBMCommonFunctions.SetControlsEnabledState(upnlWorkOrderControl.ContentTemplateContainer, bstate);
        }
        protected void btnEditWorkOrder_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                SetControlEnabledState(true);
                btnEditWorkOrder.Visible = false;
                btnSaveWorkOrder.Visible = true;
                btnRemoveWorkOrder.Visible = true;
                //btnCancel.Visible = true;
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }

        private void PushWorkOrderToScheduler(int companyid, int WorkOrderid)
        {
            SqlCommand sqlCmd = new SqlCommand();
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspPushWorkOrderToScheduler");
            SQLHelper.ExecuteScalarCmd(sqlCmd);
            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
        }
        protected void btnSaveWorkOrder_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;
            int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);

            //Save WorkOrder
            int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
            int ProjectId = hfProjectId.Value == "" ? 0 : Convert.ToInt32(hfProjectId.Value);
            string InvoiceNo = txtInvoiceNo.Text;
            string TicketNo = txtTicketNo.Text;

            int BillingContactId = ddlBillingContactId.SelectedValue == "" ? 0 : Convert.ToInt32(ddlBillingContactId.SelectedValue);
            string Term = txtTerm.Text.Trim();
            string PONumber = txtPONumber.Text.Trim();
            string AdditionalInstruction = txtAdditionalInstruction.Text.Trim();

            string WorkOrderName = txtWorkOrderName.Text.Trim();
            string StartDT = txtStartDate.Text + " " + txtStartTime.Text.Trim();
            string EndDT = txtEndDate.Text + " " + txtEndTime.Text.Trim();
            string Description = txtDescription.Text.Trim();
            string Response = txtResponse.Text.Trim();

            float LaborCost = txtLaborCost.Text == "" ? 0 : Convert.ToSingle(txtLaborCost.Text);
            int DiscountPercent = txtDiscountPercent.Text == "" ? 0 : Convert.ToInt32(txtDiscountPercent.Text);
            float DiscountAmount = txtDiscountAmount.Text == "" ? 0 : Convert.ToSingle(txtDiscountAmount.Text);
            float DepositAmount = txtDepositAmount.Text == "" ? 0 : Convert.ToSingle(txtDepositAmount.Text);

            string AssignTo = RSSBMCommonFunctions.GetMultiSelectValue(chkAssignTo);
            int WorkOrderTypeID = Convert.ToInt32(ddlWorkOrderType.SelectedValue);
            int ScheduleTypeID = Convert.ToInt32(ddlScheduleType.SelectedValue);
            int StatusID = Convert.ToInt32(ddlWorkOrderStatus.SelectedValue);

            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderName", SqlDbType.NVarChar, 150, ParameterDirection.Input, WorkOrderName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.NVarChar, -1, ParameterDirection.Input, Description);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Response", SqlDbType.NVarChar, -1, ParameterDirection.Input, Response);

            if (StartDT.Trim().Length > 0)
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@StartDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(StartDT));
            if (EndDT.Trim().Length > 0)
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@EndDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(EndDT));

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LaborCost", SqlDbType.Money, 0, ParameterDirection.Input, LaborCost);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@DiscountPercent", SqlDbType.SmallInt, 0, ParameterDirection.Input, DiscountPercent);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@DiscountAmount", SqlDbType.Money, 0, ParameterDirection.Input, DiscountAmount);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@DepositAmount", SqlDbType.Money, 0, ParameterDirection.Input, DepositAmount);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@AssignTo", SqlDbType.NVarChar, 100, ParameterDirection.Input, AssignTo);

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@AdditionalInstructions", SqlDbType.NVarChar, 250, ParameterDirection.Input, AdditionalInstruction);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Terms", SqlDbType.NVarChar, 250, ParameterDirection.Input, Term);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@PONumber", SqlDbType.NVarChar, 50, ParameterDirection.Input, PONumber);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@BillingContactId", SqlDbType.Int, 0, ParameterDirection.Input, BillingContactId);

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderTypeId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderTypeID);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@AppointmentTypeId", SqlDbType.Int, 0, ParameterDirection.Input, ScheduleTypeID);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderStatusId", SqlDbType.Int, 0, ParameterDirection.Input, StatusID);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, ProjectId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@InvoiceNo", SqlDbType.NVarChar, 10, ParameterDirection.Input, InvoiceNo);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@TicketNo", SqlDbType.NVarChar, 10, ParameterDirection.Input, TicketNo);

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);

            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveWorkOrder");
            SQLHelper.ExecuteScalarCmd(sqlCmd);
            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
            //End Save

            PushWorkOrderToScheduler(CompanyId, WorkOrderId);
            ucModalActionMessageControl.ShowModal("WorkOrder Successfully Saved!", "RSWorkOrderDetail.aspx?locationid=" + LocationId + "&workorderid=" + returnValue, true);
        }

        protected void btnRemoveWorkOrder_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int CompanyId = userIdentity.RSCompanyId;
                int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
                int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);
                int ProjectId = hfProjectId.Value == "" ? 0 : Convert.ToInt32(hfProjectId.Value);

                if (CompanyId > 0 && WorkOrderId > 0 && LocationId > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderid", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "[rs_uspDeleteWorkOrder]");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    ucModalActionMessageControl.ShowModal("WorkOrder and Associated Tasks Deleted Successfully!", "~/RS/SBM/RSLocationHistoryWorkOrders.aspx?locationid=" + LocationId, true);
                }
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }

        protected void btnGenerateInvoice_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;
            int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
            int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);

            if (userIdentity.RSCanWrite)
            {
                UpdateWorkOrderInvoiceStatus(CompanyId, LocationId, WorkOrderId);
                int invoiceid = CreateNewInvoice(CompanyId, LocationId, WorkOrderId, userIdentity.RSCurrentUser);
                int locationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
                int WorkOrderid = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);
                ucModalActionMessageControl.ShowModal("Invoice Generated Successfully!", "RSWorkOrderDetail.aspx?tabindex=5&locationid=" + locationId + "&workorderid=" + WorkOrderid, true);
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }

        private void UpdateWorkOrderInvoiceStatus(int CompanyId, int LocationId, int WorkOrderId)
        {
            SqlCommand sqlCmd = new SqlCommand();
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);

            SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "UPDATE rs_tblWorkOrder SET IsInvoiced=1 WHERE workorderid=@WorkOrderid AND LocationId=@locationid AND CompanyId=@companyid");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
        }
        private int CreateNewInvoice(int CompanyId, int LocationId, int WorkOrderId, string CurrentUser)
        {
            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, CurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveInvoice");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
            return returnValue;
        }
        public bool LoadWorkOrderDataByID(int companyid, int WorkOrderid)
        {
            bool bHaveData = false;
            btnRollbackWorkOrderIntoEstimate.Visible = false;
            if (companyid > 0)
            {
                RSSBMDataLookupLoader.LoadAssignToCHK(companyid, chkAssignTo);
                RSSBMDataLookupLoader.LoadTypeDDL(companyid, "WORKORDER_CAT", ddlWorkOrderType);
                RSSBMDataLookupLoader.LoadTypeDDL(companyid, "SCHEDULE_CAT", ddlScheduleType);
                RSSBMDataLookupLoader.LoadStatusDDL(companyid, "WORKORDER_CAT", ddlWorkOrderStatus);

                if (!String.IsNullOrEmpty(Request.QueryString["locationid"]))
                {
                    int locationid = 0;
                    locationid = Convert.ToInt32(Request.QueryString["locationid"].ToString());
                    hfLocationId.Value = locationid.ToString();
                }

                if (WorkOrderid > 0)
                {
                    String strSQL = "SELECT p.WorkOrderId,i.invoiceid, p.WorkOrderName,p.Description,p.Response,p.Active,p.StartDT,p.EndDT,p.WorkOrderTypeId,p.AppointmentTypeId," +
                                    " p.InvoiceNo, p.TicketNo, p.AssignTo,p.LaborCost,p.DiscountPercent,p.DiscountAmount,p.DepositAmount,p.BillingContactId,p.WorkOrderStatusId," +
                                    " p.ProjectId,p.LocationId,p.CompanyId,p.IsInvoiced,p.AdditionalInstructions,p.PONumber,p.Terms, p.EstimateId FROM dbo.rs_tblWorkOrder p" +
                                    " left join rs_tblinvoice i on p.workorderid=i.WorkOrderid" +
                                    " WHERE p.workorderid=@WorkOrderid AND p.CompanyId=@companyid";

                    SqlCommand myCommand;
                    SqlParameter param;
                    SqlConnection myConnection;
                    myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                    myCommand = new SqlCommand(strSQL, myConnection);
                    SqlDataReader myDataReader;

                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@WorkOrderid";
                    param.Value = WorkOrderid;
                    myCommand.Parameters.Add(param);


                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@Companyid";
                    param.Value = companyid;
                    myCommand.Parameters.Add(param);

                    myConnection.Open();
                    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    if (myDataReader.HasRows)
                    {
                        myDataReader.Read();

                        ddlWorkOrderType.SelectedIndex = 0;
                        ddlScheduleType.SelectedIndex = 0;
                        ddlWorkOrderStatus.SelectedIndex = 0;

                        if (myDataReader["LocationId"] != DBNull.Value)
                        {
                            int locationid = 0;
                            locationid = int.Parse(myDataReader["LocationId"].ToString());
                            hfLocationId.Value = locationid.ToString();

                            LoadTicketDDL(companyid, locationid);
                            LoadBillingContactByLocationID(companyid, locationid);
                        }

                        txtInvoiceNo.Text = myDataReader["InvoiceNo"].ToString();
                        txtTicketNo.Text = myDataReader["TicketNo"].ToString();
                        txtWorkOrderId.Text = myDataReader["workorderid"].ToString();
                        txtWorkOrderName.Text = myDataReader["WorkOrderName"].ToString();

                        if (myDataReader["StartDT"] != DBNull.Value)
                        {
                            DateTime startdt = Convert.ToDateTime(myDataReader["StartDT"].ToString());
                            txtStartTime.Text = startdt.ToShortTimeString();
                            txtStartDate.Text = startdt.ToShortDateString();
                        }

                        if (myDataReader["EndDT"] != DBNull.Value)
                        {
                            DateTime enddt = Convert.ToDateTime(myDataReader["EndDT"].ToString());
                            txtEndTime.Text = enddt.ToShortTimeString();
                            txtEndDate.Text = enddt.ToShortDateString();
                        }

                        txtDescription.Text = myDataReader["Description"].ToString();
                        txtResponse.Text = myDataReader["Response"].ToString();
                        if (myDataReader["WorkOrderTypeID"] != DBNull.Value)
                            ddlWorkOrderType.SelectedValue = myDataReader["WorkOrderTypeID"].ToString();
                        if (myDataReader["AppointmentTypeID"] != DBNull.Value)
                            ddlScheduleType.SelectedValue = myDataReader["AppointmentTypeID"].ToString();
                        if (myDataReader["WorkOrderStatusId"] != DBNull.Value)
                            ddlWorkOrderStatus.SelectedValue = myDataReader["WorkOrderStatusId"].ToString();
                        ddlProjectId.SelectedValue = myDataReader["ProjectId"].ToString();
                        if (myDataReader["BillingContactId"] != DBNull.Value)
                            ddlBillingContactId.SelectedValue = myDataReader["BillingContactId"].ToString();
                        txtAdditionalInstruction.Text = myDataReader["AdditionalInstructions"].ToString();
                        txtPONumber.Text = myDataReader["PONumber"].ToString();
                        txtTerm.Text = myDataReader["Terms"].ToString();

                        txtLaborCost.Text = myDataReader["LaborCost"].ToString();
                        txtDiscountPercent.Text = myDataReader["DiscountPercent"].ToString();
                        txtDiscountAmount.Text = myDataReader["DiscountAmount"].ToString();
                        txtDepositAmount.Text = myDataReader["DepositAmount"].ToString();
                        RSSBMCommonFunctions.SetMultiSelectList(myDataReader["AssignTo"].ToString(), chkAssignTo);
                        hfProjectId.Value = myDataReader["ProjectId"].ToString();

                        bHaveData = true;

                        bool isInvoiced = false;
                        if (myDataReader["IsInvoiced"] != DBNull.Value)
                        {
                            isInvoiced = Convert.ToBoolean(myDataReader["IsInvoiced"]);
                        }
                        if (ddlWorkOrderStatus.SelectedItem.Text.ToLower() == "completed")
                        {
                            if (!isInvoiced)
                                btnGenerateInvoice.Enabled = true;
                            if (isInvoiced)
                            {
                                hfInvoiceId.Value = myDataReader["InvoiceId"].ToString();
                            }
                        }
                        if (myDataReader["EstimateId"] != DBNull.Value)
                        {
                            int estimateid = Convert.ToInt32(myDataReader["EstimateId"].ToString());
                            if (estimateid > 0)
                                btnRollbackWorkOrderIntoEstimate.Visible = true;
                        }
                        if (!isInvoiced)
                        {
                            btnRollbackWorkOrderIntoEstimate.Enabled = true;
                        }

                        if (Request.QueryString["action"] == "add")
                        { ; }
                        else
                        {
                            SetControlEnabledState(false);
                        }

                    }
                    myConnection.Close();
                }
                else
                {
                    if (Request.QueryString["locationid"] != null)
                    {
                        int locationid = Convert.ToInt32(Request.QueryString["locationid"].ToString());
                        int locationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
                        LoadTicketDDL(companyid, locationid);
                        LoadBillingContactByLocationID(companyid, locationid);
                    }
                }
            }
            return bHaveData;
        }

        private string GetLocationFullAddress(int companyid, int locationid)
        {
            string fulladdress = string.Empty;
            String strSQL = "select LocationId,LocationName,Street,City,County,State,Country,Zip,Active,Note,CompanyId from rs_tblLocation where locationid=@locationid and companyid=@companyid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@locationid";
            param.Value = locationid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (myDataReader.HasRows)
            {
                myDataReader.Read();
                //fulladdress = myDataReader["LocationName"].ToString() + " - ";
                fulladdress = myDataReader["Street"].ToString() + ", ";
                fulladdress = fulladdress + myDataReader["City"].ToString() + ", ";
                fulladdress = fulladdress + myDataReader["State"].ToString() + " " + myDataReader["Zip"].ToString();
            }
            myConnection.Close();
            return fulladdress;
        }

        private void LoadBillingContactByLocationID(int companyid, int locationid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "select c.ContactId, cast(c.ContactId as varchar(5)) + ' - ' + c.FirstName + ' ' + c.lastname as ContactName, c.BillingLocationId from rs_tblContact c inner join rs_tblContactLocation cl on c.contactid=cl.contactid where cl.LocationId=@locationid and cl.CompanyId=@companyid";
            SqlParameter param;
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@locationid";
            param.Value = locationid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlBillingContactId.Items.Clear();
            ddlBillingContactId.DataSource = myDataReader;
            ddlBillingContactId.DataTextField = "contactname";
            ddlBillingContactId.DataValueField = "contactid";
            ddlBillingContactId.DataBind();
            ddlBillingContactId.Items.Insert(0, new ListItem("< Please select >", "0"));
            myConnection.Close();
        }

        private void LoadTicketDDL(int companyid, int locationid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "SELECT ProjectId FROM rs_tblProject WHERE CompanyID=@companyid AND LocationID=@locationid ORDER BY ProjectId Desc";
            SqlParameter param;
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@locationid";
            param.Value = locationid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlProjectId.Items.Clear();
            ddlProjectId.DataSource = myDataReader;
            ddlProjectId.DataTextField = "ProjectId";
            ddlProjectId.DataValueField = "ProjectId";
            ddlProjectId.DataBind();
            ddlProjectId.Items.Insert(0, new ListItem(" ", "0"));
            myConnection.Close();
        }
       
        protected void btnRollbackWorkOrderIntoEstimate_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;
            int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
            int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);

            if (CompanyId > 0 && WorkOrderId > 0 && LocationId > 0)
            {
                SqlCommand sqlCmd = new SqlCommand();
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspRollbackWorkOrderToEstimate");
                SQLHelper.ExecuteScalarCmd(sqlCmd);
                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                if(returnValue > 0)
                    ucModalActionMessageControl.ShowModal("WorkOrder Successfully Rollback Into Estimate!", "RSLocationHistoryWorkOrders.aspx?locationid=" + LocationId, true);
            }

        }
        
    }
}